<html>
<body>

<h1>Calculator</h1>
<form action="calculator.php" method="GET">
<input type="text" name="expr" />
<input type="submit" value="Calculate" />
</form>

<?php

$equ=$_GET["expr"]; // Gets user input

if ($equ != null)
{
	$temp_equ=$equ;
  	$length=strlen($equ);

	$valid=true; // Counter to check whether input is valid
	$div_zero=false; // Counter to check if dividing by zero

  	for ($i=0; $i<$length; $i++)
    	{
		$temp=substr($temp_equ, $i, 1); // Checking each character in input

		if (!is_numeric($temp) and $temp != '+' and $temp != '-' and $temp != '*' and $temp != '/' and $temp != '.' and $temp != ' ')
		{
			// Valid inputs are numbers, '+', '-', '*', '/', and '.'.
			$valid=false; // Character not a valid input
		}

		// The next character to be used by switch statement
		$temp_next = '';
		if (($i + 1) != $length)
			$temp_next = substr($temp_equ, $i + 1, 1); // Only if not at the last character of string
		
		// To check for invalid sequence of operators
		switch ($temp)
		{
		case '+':
			if ($temp_next == '' or $temp_next == '+' or $temp_next == '*' or $temp_next == '/')
				$valid=false;
			break;
		case '-':
			if ($temp_next == '' or $temp_next == '-' or $temp_next == '*' or $temp_next == '/')
				$valid=false;
			break;
		case '*':
			if ($temp_next == '' or $temp_next == '*' or $temp_next == '/')
				$valid=false;
			break;
		case '/':
			if ($temp_next == '' or $temp_next == '*' or $temp_next == '/')
				$valid=false;
			else if ($temp_next == '0')
				$div_zero=true; // Special case if trying to divide by zero
			break;
		case '.':
			if ($temp_next == '.' or $temp_next == ' ')
				$valid=false;
			break;
		case '0':
			if (($i + 2) != $length)
			{
				$temp_sub = substr($temp_equ, $i, 3);
				if ($temp_sub == "0+0" or $temp_sub == "0-0" or $temp_sub == "0*0")
				{
					$temp_equ=substr_replace($temp_equ, "0", $i, 3);
					$i = $i + 2;
				}
			}
		default:
			break;
		}
    	}

	echo '<h2>Result</h2>';
	if ($valid == true and $div_zero == false)
		eval("\$ans = $temp_equ;"); // Evaluate the input

	if ($ans != null and $valid == true and $div_zero == false)
		echo $equ . " = " . $ans; // If eval succeeded and all inputs valid
	else if ($div_zero == true and $valid == true)
		echo $equ . " ="; // If input tries to divide by zero
	else
	{
		if ($temp_equ == '0')
			echo $equ . " = 0";
		else
			echo "Invalid input expression: " . $equ;
	}
}

?>

</body>
</html>
